<?php

/**
 * Base project form.
 *
 * @package    reclamos
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: BaseForm.class.php 20147 2009-07-13 11:46:57Z FabianLange $
 */
class BaseForm extends sfFormSymfony
{

  /**
   * Make a set of fields of this form toggleable. That is, $fields is an
   * associative array with the toggler fields as keys and the subject fields
   * for each toggler as values.
   *
   * @see self::makeToggleable()
   *
   * @param array  $fields    The array of fields.
   * @param string $form_name An optional name to be used as prefix of DOM ids.
   * @param array  $options   Options for the makeToggleable() method.
   */
  protected function makeToggleables($fields, $form_name = null, $options = array())
  {
    $js = '';
    $js_field_name = 'toggleable_js_' . time();
    $options = array_merge(array(
      'form_prefix' => $form_name === null ? $this->getName() : $form_name
      ), $options);

    foreach ($fields as $toggler => $subjects)
    {
      $js .= $this->makeToggleable($toggler, $subjects, $options);
    }

    $js = sprintf('jQuery(function() { %s });', $js);

    $this->setWidget($js_field_name, new sfWidgetFormScriptTag(array('script' => $js)));
    $this->setValidator($js_field_name, new sfValidatorPass());

  }

  /**
   * Get the JavaScript snippet that makes $subjects conditioned by $toggler.
   *
   * Available options are:
   *  * form_prefix: The prefix for DOM id attributes. If null, the name of
   *    the form is used.
   *  * toggle_row: Whether or not to hide/show the container row of
   *    subject fields when they are disabled/enabled.
   *
   * @param string $toggler  Name of the toggler (observed) field.
   * @param mixed  $subjects Name(s) of the subject field(s). string or array.
   * @param array  $options  Non-required options.
   *
   * @return string
   */
  protected function makeToggleable($toggler, $subjects, $options = array())
  {
    $options = array_merge(array(
      'form_prefix' => null,
      'toggle_row' => true
      ), $options);

    if (!is_array($subjects))
    {
      $subjects = array($subjects);
    }

    $js = <<<JAVASCRIPT
jQuery('#%toggler_id%').change(function() {
  if (jQuery(this).is(':checked'))
  {
    jQuery.each([ %subject_ids% ], function() {
      jQuery('#'+this).removeAttr('disabled')%show_row%;
    });
  }
  else
  {
    jQuery.each([ %subject_ids% ], function() {
      jQuery('#'+this).attr('disabled', true)%hide_row%;
    });
  }
}).change();

JAVASCRIPT;

    return strtr($js, array(
        '%toggler_id%' => sprintf('%s_%s', $options['form_prefix'], $toggler),
        '%subject_ids%' => implode(', ', array_map(create_function('$name', sprintf('return "\'%s_".$name."\'";', $options['form_prefix'])), $subjects)),
        '%hide_row%' => $options['toggle_row'] ? '.closest(\'tr\').hide()' : '',
        '%show_row%' => $options['toggle_row'] ? '.closest(\'tr\').show()' : ''
      ));

  }

}
